<div class="page-wrapper">
    <div class="header">
        <a href="javascript:history.back();" class="left"><i class="icon-back"></i><span class="waiter-order-text">菜单</span></a>
        <div id="order-preview-title" class="title">确认订单</div>
    </div>

    <div class="order-body">
        <div id="waiter-food-list" class="food-list">

        </div>
        <div id="repeat-preview-food-item" class="food-item" style="display: none;">
            <div class="menu-name"><span class="name"></span></div>
            <span class="unitPrice"></span>
            <span class="preview-count"></span>
        </div>
        <div id="repeat-order-food-item" class="food-item" style="display: none;">
            <div class="menu-name"><span class="name"></span><span class="count"></span></div>
            <span class="unitPrice"></span>
            <span class="isDone"><i class="icon-remove"></i></span>
        </div>

        <div class="summary" style="display: none">
            <div class="pivot">
                <div class="pivot-left"></div>
                <div class="pivot-center"></div>
                <div class="pivot-right"></div>
            </div>
            <div class="summary-content">
                <div class="summary-line">
                    <span class="summary-left">小计:</span>
                    <span id="total" class="summary-right"></span>
                </div>
                <div class="summary-line">
                    <span class="summary-left">优惠:</span>
                    <span id="coupon" class="summary-right">无</span>
                </div>
                <div class="total">总计：<span id="final-total" class="price"></span></div>
                <button id="confirm" style="display: none;" class="btn book">下单</button>
                <div class="btn-group">
                    <button id="order-left-btn" class="btn">拒绝</button>
                    <button id="order-right-btn" class="btn">确定</button>
                </div>
            </div>

        </div>

    </div>

    <script>
        (function (window, document, $) {
            'use strict';
            console.log('waiter_order.html');

            var from = spa.getParam('from');
            $('.header .waiter-order-text').text(from || '菜单');

            //提交订单时返回的orderId
            var postOrderId = undefined;

            /*
            * 设置标题栏
            */
            function setWaiterOrderTitle(text){
                $('#order-preview-title').text(text);
            }
             /**
             *  下单接口
             */
            function postOrder() {
                var $floatUI = common.showLoading('下单中,请稍后');
                var order = cart.getOrder();
                console.log(order);
                console.log(window.userId + ' ' + window.storeId);
                $.post('/waiterOrder/api/order/', order, function (data) {
                    common.dismissLoading($floatUI);
                    console.log(data);
                    if (data && data.status === 'success') {
                        cart.clear();
                        common.toast('下单成功');
                        postOrderId = data.order.orderId;
                        showOnlineOrder(data.order,data.menus);
                    } else if (data && data.status == 'error') {
                        common.toast('订单数据异常');
                    }else {
                        //提交订单失败
                        common.toast('订单提交失败，请确认网络正常...');
                    }
                }, 'json');
            }

            /**
             * 清空列表
             */
            function clearItem() {
                $('#preview-food-list').html('');
            }

            /**
             *  去掉【拒绝】【确定】【下单】【结单】等相应时间
             */
            function resetButtons() {
                $('.btn-group').hide();
                $('#confirm').hide();
                $('#confirm').off('click');
                $('#order-left-btn').off('click');
                $('#order-right-btn').off('click');
            }
            /**
             * 取消订单
             */
            function refuse(id){
                console.log('refuse ' + id);

                if(confirm("您确定拒绝此订单吗？")){
                    $.getJSON('/waiterOrder/api/refuseOrder/'+id,'',function (data) {
                        if(data.status === 'success'){
                            common.toast('订单已拒绝');
                            history.back();
                        }else{
                            common.toast('拒绝订单失败');
                        }
                    });
                }
            }
            /**
             * 接收订单
             */
            function accept(id){
                console.log('accept ' + id);
                $.getJSON('/waiterOrder/api/acceptOrder/'+id,'',function(data){
                   if(data.status === 'success'){
                       common.toast('订单已确定');
                       history.back();
                   } else{
                        common.toast('订单确定失败');
                   }
                });
            }

            /*
             * 显示在线订单信息
             */
            function showOnlineOrder(order,menus) {
                clearItem();
                resetButtons();
                console.log(order);
                if(order.state == OrderState.unconfirmed){ //服务员未确认订单
                    $('.btn-group').show();
                    var id = order.orderId;
                    $('#order-left-btn').text('拒绝').on('click',function(){
                        refuse(id);
                    });
                    $('#order-right-btn').text('确定').on('click',function(){
                        accept(id);
                    });
                }else if (order.state == OrderState.wechat_payed) { //已结账订单 --- 微信端
                    $('#confirm').text('已结单').addClass('payed').show();
                } else if(order.state == OrderState.confirmed){ //已确认订单，点击按钮-> 收款页面

                    if(spa.getParam('action') === 'waiter_order'){
                        $('#confirm').text('收款').show().on('click',function(){
                            //显示收款二维码
                            location.href = "#action=waiter_qr&tableId="+order.tableId;
                        });
                    }
                }else if(order.state == OrderState.unconfirmed){
                    $('.btn-group').fadeIn();
                    $('#order-left-btn').click(function(){
                        refuse(order.orderId);
                    });
                    $('#order-right-btn').click(function(){
                        accept(order.orderId);
                    });
                }
                if(!menus || !menus.length) return;

                var $list = $('#waiter-food-list');
                $list.html('');
                $.each(menus, function (index, item) {
                    var $item = cloneOrderItem();
                    var unitPrice = item.foodDetail.unitPrice;
                    var count = item.count;
                    var price = unitPrice * count;
                    var name = item.foodDetail.name;
                    $item.attr('map-id',item.id);
                    $item.find('.menu-name .name').text(name);
                    $item.find('.unitPrice').text('￥' + unitPrice);
                    $item.find('.count').text('x' + count);
                    $item.find('.price').text(price);
                    if(item.removeFlag == 0){
                        $item.find('.icon-remove').on('click',removeOrderItem);
                    }else{
                        $item.addClass('removed');
                        $item.find('.isDone').text('已退');
                    }

                    $list.append($item);
                });

                showOrderSummary(order);
            }

            function showOrderSummary(data) {
                var originalPrice = data.originalPrice;
                var price = data.price;
                $('#total').text('￥' + originalPrice);
                $('#coupon').text(originalPrice == price ? '无' : '￥' + (originalPrice - price).toFixed(1));
                $('#final-total').text('￥' + price);

                $('.summary').show();
            }


            function removeOrderItem(){
                var $item = $(this).parents('.food-item');
                if(confirm('确定要退订['+$item.find('.menu-name .name').text()+']?')){
                    //退订
                    var mapId = $item.attr('map-id');
                    $.getJSON('/waiterOrder/api/delteMenuItem/'+mapId,'',function(data){
                        console.log(data);

                        if(data.status == 'success'){
                            $item.addClass('removed');
                            $item.find('.isDone').text('已退');

                            showOrderSummary(data.order);
//                            var orderId = spa.getParam('orderId');
//                            orderByOrderId(orderId);
                        }else{

                        }

                    }).fail(function(){

                    });
                }
            }

            /**
             * 显示购物车数据，并可以下单
             */
            function showCartOrder() {

                if(cart.getCount() == 0) return;

                resetButtons();
                $('#confirm').text('下单')
                        .removeClass('pay')
                        .on('click',function(){ //下单
                            postOrder();
                        })
                        .show();
                console.log(cart);
                var foods = cart.getOrder().foods;
                var $list = $('#waiter-food-list').html('');
                console.log($list);
                $(foods).each(function (key, food) {
                    var $item = clonePreviewItem();
                    $item.find('.menu-name .name').text(food.name);
                    $item.find('.unitPrice').text('￥' + food.price);
                    $item.find('.preview-count').text(food.count);
                    $item.find('.price').text('￥' + (food.price * food.count));
                    $list.append($item);
                });

                var price = cart.getPrice();
                var oPrice = cart.originalPrice();
                $('#total').text('￥' + oPrice);
                if (oPrice > price) {
                    $('#coupon').text('￥' + (oPrice - price).toFixed(1));
                } else {
                    $('#coupon').text('无');
                }
                $('#final-total').text('￥' + price);
                $('.summary').show();
            }

            var $repeatItem = undefined;

            function clonePreviewItem() {
                if (!$repeatItem) {
                    $repeatItem = $('#repeat-preview-food-item');
                }
                var $item = $repeatItem.clone();
                $item.attr('id', '');
                $item.show();
                return $item;
            }

            var $repeatOrderItem = undefined;

            function cloneOrderItem() {
                if (!$repeatOrderItem) {
                    $repeatOrderItem = $('#repeat-order-food-item');
                }
                var $item = $repeatOrderItem.clone();
                $item.attr('id', '');
                $item.show();
                return $item;
            }

            /**
             * 预览购物车数据
             */
            function preview() {
                setWaiterOrderTitle('菜单预览');
                showCartOrder();
            }

            /**
             * 订单【加菜】，【结账】等
             */
            function orderByTableId(tableId) {
                console.log(tableId);
                $('#order-preview-title').text('结账');
                $.get('/api/getorder/table/' + tableId, function (data) {
                    showOnlineOrder(data);
                });
            }

            function orderByOrderId(orderId,showsummary) {
                $('#order-preview-title').text('结账');
                $.get('/waiterOrder/api/getParentOrderById/' + orderId, function (data) {
                    if(data && data.order){
                        if(showsummary){ //删除订单的时候，只需要改变summary即可
                            showOrderSummary(data.order);
                        }else{
                            showOnlineOrder(data.order,data.menu);
                        }
                    }
                });
            }

            function showSubOrder(subOrderId) {
                $('#order-preview-title').text('审核订单');
                $.get('/waiterOrder/api/getSubOrderById/' + subOrderId, function (data) {
                    if(data && data.order){
                        console.log(data);
                        showOnlineOrder(data.order,data.menu);
                    }
                });
            }

            function showOrder() {
                var tableId = spa.getParam('tableId');
                var orderId = spa.getParam('orderId');
                var subOrderId = spa.getParam('subOrderId');
                if(tableId){
                    orderByTableId(tableId);
                }else if(orderId){
                    orderByOrderId(orderId);
                }else if(subOrderId){
                    showSubOrder(subOrderId);
                }
            }

            var action = spa.getParam('action');
            if (action == 'waiter_preview') { //购物车预览
                preview();
            } else if (action == 'waiter_order') { //订单预览
                showOrder();
            }

            spa.addResumeCallback(function(){
                console.log('waiter_order');
                var orderId = spa.getParam('orderId') || postOrderId;
                if(orderId){
                    orderByOrderId(orderId);
                }
            });


        }(window, document, $));
    </script>
</div>